from flask import Blueprint, Response, request
from bs4 import BeautifulSoup as bs
import json
import re
import Net


api_360 = Blueprint('api_360', __name__)

server_host = 'http://132.232.4.22:8080'


class Result:

    def __init__(self, state=-1, msg='', zh='', data=None):
        self.state = state
        self.msg = msg
        self.zh = zh
        if data is None:
            self.data = []
        else:
            self.data = data

    def json(self):
        result = json.dumps(self.__dict__, ensure_ascii=False)
        return Response(response=result, mimetype='application/json')


class Bean:

    def __init__(self, title, image, tag, href, router=None):
        self.title = title
        self.image = image
        self.tag = tag
        self.href = href
        self.router = router


class Site:

    def __init__(self, site, title, href):
        self.site = site
        self.title = title
        self.href = href


class Num:

    def __init__(self, num, href):
        self.num = num
        self.href = href


def json_format(url):
    data = Net.get_html(url).text
    pattern = re.compile('(.*?){"data', re.S)
    result = '{"data' + re.sub(pattern, '', data)
    obj = json.loads(result)
    result = json.dumps(obj, ensure_ascii=False)
    return result


def get_data(cid, tid, page):

    '''
    :param cid: 3 , 4, 5, 6 [电视剧，电影, 综艺, 动漫]
    :param tid: 筛选列表返回tid
    :param page: 20*(page-1)
    '''

    _type = ['tv', 'mv', 'tvs', 'ct']

    page = str(20 * (int(page)-1))
    url = 'http://android.api.360kan.com/channel/?cid='+cid+'&tid='+tid+'&start='+page+'&method=channel.datas&ver=148'

    try:
        json_str = json_format(url)
        obj = json.loads(json_str)
        datas = obj['data']['data']['datas']

        if len(datas) > 0:
            array = []
            for data in datas:
                id = server_host + '/360/' + _type[int(cid)-3] + '/site?vid=' + data['id']
                title = data['title']
                image = data['cover']
                if data['epiname'] == '期':
                    if data['upinfo'] == 0:
                        tag = '评分:' + data['score']
                    else:
                        if data['finish'] == 0:
                            tag = '更新至' + data['upinfo'] + '集'
                        else:
                            tag = data['upinfo'] + '集全'
                else:
                    tag = data['epiname']
                bean = Bean(title, image, tag, id)
                array.append(bean.__dict__)
            # print(Data('success', '', array)._json())
            result = Result(1, 'get data success', '获取数据成功', array).json()
        else:
            result = Result(msg='get data error', zh='获取数据出错').json()

    except Exception:
        result = Result(msg='get data error', zh='获取数据出错').json()
    return result


def get_tv_ct_site(_type, vid, category):

    '''
    :param _type: tv ct [电视, 动漫]
    :param vid:
    category: 2,4 [电视, 动漫]
    '''

    url = 'https://www.360kan.com/' + _type + '/' + vid + '.html'

    try:
        respond = Net.get_html(url).text

        pattern = re.compile("playsite:(.*?)],", re.S)
        json_d = '{"playsite":' + re.findall(pattern, respond)[0] + ']}'

        obj = json.loads(json_d)

        array = []
        for lis in obj['playsite']:
            site = Site(lis['ensite'], lis['cnsite'], server_host + '/360/' + _type + '/list?site=' + lis['ensite'] + '&vid=' + vid + '&category=' + category)
            array.append(site.__dict__)
            # print(lis['ensite'] + ' ' + lis['cnsite'])
        result = Result('success', 'get data success', '获取数据成功', array).json()
    except Exception:
        result = Result(msg='get data error', zh='获取数据出错').json()
    return result


def get_tv_ct_list(site, vid, category):

    url = 'https://www.360kan.com/cover/switchsite?site=' + site + '&id=' + vid + '&category=' + str(category)

    result = Result(msg='get data error', zh='获取数据出错').json()

    try:
        respond = Net.get_html(url).text
        res = re.findall('{"data":"(.*?)",', respond)[0]
        res = re.sub(r'\\', '', res)

        divs = re.findall('<div class="num-tab-main g-clear js-tab".*?>(.*?)</div>', res)

        array = []
        for div in divs:

            # print(str(div))
            pattern = re.compile('<a data-num="(.*?)".*?href="(.*?)">', re.S)

            items = re.findall(pattern, str(div))

            for item in items:
                num = Num(item[0], item[1])
                array.append(num.__dict__)
            result = Result('success', 'get data success', '获取数据成功', array).json()

    except Exception:
        result = Result(msg='get data error', zh='获取数据出错').json()
    return result


@api_360.route('/')
def index():
    return Result(state='success', msg='success').json()


@api_360.route('/tv')
def tv():
    tid = request.args.get('tid')
    page = request.args.get('page')
    if tid is None:
        tid = 'all'
    if page is None:
        page = '1'
    return get_data('3', tid, page)


@api_360.route('/mv')
def movie():
    tid = request.args.get('tid')
    page = request.args.get('page')
    if tid is None:
        tid = 'all'
    if page is None:
        page = '1'
    return get_data('4', tid, page)


@api_360.route('/tvs')
def tvs():
    tid = request.args.get('tid')
    page = request.args.get('page')
    if tid is None:
        tid = 'all'
    if page is None:
        page = '1'
    return get_data('5', tid, page)


@api_360.route('/ct')
def ct():
    tid = request.args.get('tid')
    page = request.args.get('page')
    if tid is None:
        tid = 'all'
    if page is None:
        page = '1'
    return get_data('6', tid, page)


@api_360.route('/tv/site')
def get_tv_site():

    vid = request.args.get('vid')
    if vid is not None and len(vid) > 0:
        return get_tv_ct_site('tv', vid, '2')
    else:
        return Result('error', 'vid is null', 'vid 为空').json()


@api_360.route('/ct/site')
def get_ct_site():

    vid = request.args.get('vid')
    if vid is not None and len(vid) > 0:
        return get_tv_ct_site('ct', vid, '4')
    else:
        return Result('error', 'vid is null', 'vid 为空').json()


@api_360.route('/mv/site')
def get_mv_site():

    vid = request.args.get('vid')
    if vid is not None and len(vid) > 0:
        url = 'https://www.360kan.com/m/' + vid + '.html'

        try:
            respond = Net.get_html(url).text

            pattern = re.compile('class="btn js-site ea-site ea-site-(.*?)" href="(.*?)">(.*?)</a>', re.S)
            data = re.findall(pattern, respond)

            array = []
            for lis in data:
                site = Site(lis[0], re.sub('\(付费\)', '', lis[2]), server_host + '/360/mv/list?vid=' + lis[1])
                array.append(site.__dict__)
                # print(lis[0] + ' ' + re.sub('\(付费\)', '', lis[1]))
            result = Result('success', 'get data success', '获取数据成功', array).json()
        except Exception:
            result = Result(msg='get data error', zh='获取数据出错').json()
        return result
    else:

        return Result('error', 'vid is null', 'vid 为空').json()


@api_360.route('tvs/site')
def get_tvs_site():

    vid = request.args.get('vid')
    if vid is not None and len(vid) > 0:
        url = 'https://www.360kan.com/va/' + vid + '.html'

        try:
            respond = Net.get_html(url).text

            pattern = re.compile('<span class="ea-site ea-site-(.*?) btn">(.*?)</span>', re.S)
            data = re.findall(pattern, respond)

            array = []
            for lis in data:
                site = Site(lis[0], lis[1], server_host + '/360/tvs/list?site=' + lis[0] + '&vid=' + vid)
                array.append(site.__dict__)
                # print(lis[0] + ' ' + lis[1])

            result = Result('success', 'get data success', '获取数据成功', array).json()
        except Exception:
            result = Result(msg='get data error', zh='获取数据出错').json()
        return result

    else:
        return Result('error', 'vid is null', 'vid 为空').json()


@api_360.route('tv/list')
def get_tv_list():

    site = request.args.get('site')
    vid = request.args.get('vid')
    category = request.args.get('category')
    if len(site) and len(vid) and len(category) > 0:
        return get_tv_ct_list(site, vid, category)
    else:
        return Result('error', 'param is null', '参数不能为空').json()


@api_360.route('ct/list')
def get_ct_list():

    site = request.args.get('site')
    vid = request.args.get('vid')
    category = request.args.get('category')
    if len(site) and len(vid) and len(category) > 0:
        return get_tv_ct_list(site, vid, category)
    else:
        return Result('error', 'param is null', '参数不能为空').json()


@api_360.route('tvs/list')
def get_tvs_list():

    site = request.args.get('site')
    vid = request.args.get('vid')

    if len(site) and len(vid) > 0:
        url = 'https://www.360kan.com/cover/zongyilist?id=' + vid + '&site=' + site + '&do=switchsite&isByTime=false'

        result = Result(msg='get data error', zh='获取数据出错').json()

        try:
            respond = Net.get_html(url).text
            res = re.findall('{"data":"(.*?)",', respond)[0]
            res = re.sub(r'\\', '', res)

            divs = re.findall('<ul class="list w-newfigure-list g-clear js-year-page" style=.*?">(.*?)</ul>', res)

            array = []
            for div in divs:
                pattern = re.compile("href='(.*?)'.*?class='w-newfigure-hint'>(.*?)</span>", re.S)

                items = re.findall(pattern, str(div))
                for item in items:
                    num = Num(re.sub('u671f', '期', item[1]), item[0])
                    array.append(num.__dict__)
                result = Result('success', 'get data success', '获取数据成功', array).json()
        except Exception:
            result = Result(msg='get data error', zh='获取数据出错').json()
        return result

    else:
        return Result('error', 'param is null', '参数不能为空').json()


@api_360.route('/mv/list')
def get_mv_list():
    vid = request.args.get('vid')

    array = [Num('播放', vid).__dict__]

    return Result('success', 'get data success', '获取数据成功', array).json()
